package com.ct.rbac.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ct.rbac.mapper.SysRoleMenusMapper;
import com.ct.rbac.orm.SysRoleMenusDO;
import com.ct.rbac.repository.ISysRoleMenusRespontory;
import com.ct.repository.commons.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-13
 */
@Service
public class SysRoleMenusRespontoryImpl extends BaseServiceImpl<SysRoleMenusMapper, SysRoleMenusDO> implements ISysRoleMenusRespontory {

    /**
     * 判断菜单是否被角色引入
     * @param menuId
     * @return
     */
    @Override
    public Boolean countMenuRole(Long menuId){
        LambdaQueryWrapper<SysRoleMenusDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleMenusDO::getMenuId,menuId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 判断角色是否引入
     * @param roleId
     * @return
     */
    @Override
    public Boolean countRoleMenu(Long roleId){
        LambdaQueryWrapper<SysRoleMenusDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleMenusDO::getRoleId,roleId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 角色授权菜单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bindMenus(Long roleId, List<Long> menuIds){
        // 先删除角色对应的菜单
        LambdaQueryWrapper<SysRoleMenusDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleMenusDO::getRoleId,roleId);
        this.remove(lambdaQueryWrapper);

        // 添加角色对应的菜单
        List<SysRoleMenusDO> sysRoleMenusDOS = menuIds.stream().map(menuId -> {
            SysRoleMenusDO sysRoleMenusDO = new SysRoleMenusDO();
            sysRoleMenusDO.setRoleId(roleId);
            sysRoleMenusDO.setMenuId(menuId);
            return sysRoleMenusDO;
        }).collect(Collectors.toList());

        return this.saveBatch(sysRoleMenusDOS);
    }


}
